package com.code.leetcode.offer;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/8/4 12:49
 */
public class The57_双指针 {
    /**
     * 效率低下
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSumLow(int[] nums, int target) {
        Set<Integer> map = new HashSet<>();
        for (int num : nums) {
            if(!map.contains(num)) map.add(target - num);
            else {
                return new int[]{num, target - num};
            }
        }
        return new int[]{};
    }

    /**
     * 双指针法
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int sum = nums[left] + nums[right];
            if (sum > target) right--;
            else if (sum < target) left++;
            else return new int[]{nums[left], nums[right]};
        }
        return new int[]{};
    }

}
